package com.ky.manage.fragment;

import android.content.Intent;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jpeng.jptabbar.JPTabBar;
import com.ky.manage.R;
import com.ky.manage.activity.msg.MsgListActivity;
import com.ky.manage.adapter.MsgCenterAdapter;
import com.ky.manage.base.BaseFragment;
import com.ky.manage.constant.OverallData;
import com.ky.manage.model.MsgCenterItemModel;
import com.ky.manage.model.MsgCntChangeEvent;
import com.ky.manage.model.response.MsgListResp;
import com.ky.manage.utils.ToastUtils;
import com.ky.manage.utils.ZyUtils;
import com.ky.manage.utils.http.AsyncHttpUtils;
import com.ky.manage.utils.http.BusinessHttpReqUtils;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * 消息中心页
 */
public class MsgCenterFragment extends BaseFragment {
    private JPTabBar mTabBar;
    private MsgCenterAdapter mMsgCenterAdapter;
    private RefreshLayout refreshLayout;

    @Override
    protected int layoutId() {
        return R.layout.layout_msg_center_fragment;
    }

    @Override
    protected void initView(View rootView) {
        RecyclerView msgRecyclerView = findView(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        msgRecyclerView.setLayoutManager(linearLayoutManager);
        mMsgCenterAdapter = new MsgCenterAdapter(R.layout.layout_msg_center_item, new ArrayList<>());
        mMsgCenterAdapter.setEmptyView(R.layout.layout_empty_data);
        mMsgCenterAdapter.setOnItemClickListener((adapter , view , position) -> {
            //条目点击
            jump2MsgListPage(position);
        });
        msgRecyclerView.setAdapter(mMsgCenterAdapter);
        mMsgCenterAdapter.notifyDataSetChanged();

        refreshLayout = findView(R.id.refreshLayout);
        refreshLayout.setRefreshHeader(new ClassicsHeader(mContext));
        refreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
        refreshLayout.autoRefresh();
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            reqMsgListInfoData();
        });
        refreshLayout.setEnableLoadMore(false);
    }

    private boolean mIsReqListData = false;

    private void reqMsgListInfoData() {
        if (mIsReqListData) {
            return;
        }
        mIsReqListData = true;
        RequestParams requestParams = new RequestParams();
        requestParams.put("isRead", 1);//阅读状态(0已读， 1未读)
        requestParams.put("status", 0);//公告状态（0正常 1关闭）
        AsyncHttpUtils.getInstance().get(BusinessHttpReqUtils.SERVICE_DOMAIN + "/appApi/getNoticeList", requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                ZyUtils.getInstance().insertLog("reqMsgListInfoData", "onFailure statusCode = " +
                        statusCode + ", errorResponse = "+ responseString
                        + ", throwable = " + throwable.getMessage());
                ToastUtils.showRoundRectToast("获取消息列表数据失败：" + throwable.getMessage());
                refreshLayout.finishRefreshWithNoMoreData();
                mIsReqListData = false;
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                ZyUtils.getInstance().insertLog("reqMsgListInfoData", "onSuccess statusCode = " +
                        statusCode + ", responseString = "+ responseString);
                MsgListResp msgListResp = BusinessHttpReqUtils.getInstance().parseJsonObj
                        (responseString, MsgListResp.class);
                if (null != msgListResp) {
                    if (msgListResp.code == 200) {
                        parseMsgList2MstModel(msgListResp.rows);
                    } else if (msgListResp.code == 401){
                        //登陆失效，需重新登陆
                        BusinessHttpReqUtils.getInstance().autoPwdLogin(mContext);
                    } else {
                        ToastUtils.showRoundRectToast("获取消息列表数据失败: " + msgListResp.msg);
                    }
                } else {
                    ToastUtils.showRoundRectToast("获取消息列表数据失败");
                }
                refreshLayout.finishRefresh();
                mIsReqListData = false;
            }
        });
    }

    private void parseMsgList2MstModel(List<MsgListResp.MsgItemInfo> rows) {
        List<MsgCenterItemModel> msgCenterItemModelList = new ArrayList<>();
        MsgCenterItemModel systemNoticeItemModel = new MsgCenterItemModel();
        systemNoticeItemModel.content = "";
        systemNoticeItemModel.date = "";
        //公告类型（1通知 2公告）
        systemNoticeItemModel.type = "1";
        systemNoticeItemModel.title = "系统通知";
        msgCenterItemModelList.add(systemNoticeItemModel);
        MsgCenterItemModel systemAnnounceItemModel = new MsgCenterItemModel();
        systemAnnounceItemModel.content = "";
        systemAnnounceItemModel.date = "";
        //公告类型（1通知 2公告）
        systemAnnounceItemModel.type = "2";
        systemAnnounceItemModel.title = "系统公告";
        msgCenterItemModelList.add(systemAnnounceItemModel);
        if (null != rows && !rows.isEmpty()) {
            for (MsgListResp.MsgItemInfo msgItemInfo : rows) {
                if ("1".equals(msgItemInfo.noticeType)) {
                    systemNoticeItemModel.content = msgItemInfo.noticeTitle;
                    ++systemNoticeItemModel.cnt;
                } else if ("2".equals(msgItemInfo.noticeType)) {
                    systemAnnounceItemModel.content = msgItemInfo.noticeTitle;
                    ++systemAnnounceItemModel.cnt;
                }
            }
        }
        OverallData.sMsgCnt = systemNoticeItemModel.cnt + systemAnnounceItemModel.cnt;
        mMsgCenterAdapter.setList(msgCenterItemModelList);
        EventBus.getDefault().post(new MsgCntChangeEvent());
    }

    @Override
    protected void initData() {

    }

    private void jump2MsgListPage(int position) {
        MsgCenterItemModel msgCenterItemModel = mMsgCenterAdapter.getItem(position);
        Intent intent = new Intent(mContext, MsgListActivity.class);
        intent.putExtra("type", msgCenterItemModel.type);
        intent.putExtra("title", msgCenterItemModel.title);
        toActivity(intent);
    }
}
